const crypto = require('crypto');
const Adminuser = require('../models/admin_user');

function createAdminUser(user_name, user_pwd) {
    const userhash = crypto.createHash('sha1');
    let _usermsg;
    if (user_name && user_pwd) {
        const hash_pwd = userhash.update('s1_admin').update(user_pwd).digest('hex');
        Adminuser.fetchByName(user_name, function (err, data) {
            if (err) {
                console.log(err);
                console.log({
                    status: 'fail',
                    msg: '服务器抢修中，暂时无法注册'
                })
            } else {
                if (data.length == 0) {
                    _usermsg = new Adminuser({
                        username: user_name,
                        password: hash_pwd
                    });
                    _usermsg.save(function (err, data) {
                        if (err) {
                            console.log(err);
                            console.log({
                                status: 'fail'
                            })
                        } else {
                            console.log({
                                status: 'success'
                            })
                        }
                    })
                } else {
                    console.log({
                        status: 'fail',
                        msg: '该账号已被注册'
                    })
                }
            }
        })
    }
}

// console.log(process.argv)
if (process.argv.length < 4) {
    console.log('参数错误,用法 node create_admin_user username password')
} else {
    // db
    const dbUrl = 'mongodb://localhost:27017/xiaous2'
    var mongoose = require('mongoose');
    mongoose.set('useNewUrlParser', true);
    mongoose.set('useFindAndModify', false);
    mongoose.set('useCreateIndex', true);
    mongoose.connect(dbUrl)
    createAdminUser(process.argv[2], process.argv[3])
}